#pragma once
#include <string>
#include <iostream>
#include <jsoncpp/json/json.h>
#include "util.hpp"

#define NUM 1024

class Login
{
public:
    Login() {}

    ~Login() {}

    // 登录验证
    bool vertify(const std::string& user, const std::string& passwd)
    {
        return Util::findUser(user, passwd);
    }

    // 注册
    bool registerUser(const std::string& user, const std::string& passwd)
    {
        if (vertify(user, passwd))
        {
            std::cout << "用户名、密码已经存在" << std::endl;
            return false;
        }
        // 插入用户名、密码到数据库
        return Util::insertUser(user, passwd);
    }

    // 登录或注册
    bool registerOrLogin(const Json::Value& root)
    {
        std::string user = root["user"].asString();
        std::string passwd = root["passwd"].asString();
        int sign = root["sign"].asInt();
        bool result = false;
        switch (sign)
        {
        case 1:
            result = vertify(user, passwd);
            break;
        case 2:
            result = registerUser(user, passwd);
            break;
        default:
            std::cout << "sign值非法" << std::endl;
            break;
        }

        return result;
    }

    // 发送数据
    void sendData(int sock, const bool result)
    {
        Json::Value root;
        Json::StyledWriter writer;
        root["result"] = result;
        std::string ret = writer.write(root);
        write(sock, ret.c_str(), ret.length());
    }
};